package com.ybkj.daijia.server.controller;

import com.ybkj.daijia.common.Principal;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.server.exception.NoPermissionException;
import com.ybkj.daijia.page.Page;
import com.ybkj.daijia.server.model.Brand;
import com.ybkj.daijia.server.model.BrandType;
import com.ybkj.daijia.server.model.Car;
import com.ybkj.daijia.server.model.Car.TransmissionCase;
import com.ybkj.daijia.server.model.CarType;
import com.ybkj.daijia.server.service.BrandService;
import com.ybkj.daijia.server.service.BrandTypeService;
import com.ybkj.daijia.server.service.CarService;
import com.ybkj.daijia.server.service.CarTypeService;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.ShopService;
import java.io.FileNotFoundException;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.util.WebUtils;

/**
 * @author Shine
 */
@Controller
@RequestMapping(value = "car")
public class CarController {

    private static final Logger logger = LoggerFactory.getLogger(CarController.class);

    @Autowired
    private CarService carService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private BrandTypeService brandTypeService;

    @Autowired
    private CarTypeService carTypeService;

    @Autowired
    private CompanyService companyService;


    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;

    @Autowired
    private ShopService shopService;

    @RequestMapping(value = "list", method = RequestMethod.GET)
    public ModelAndView list(@RequestParam(required = false, value = "param") String param) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("car")) {
            ModelAndView mv = new ModelAndView();
            mv.setViewName("car/list");

            Page<Car> page = carService.findCarResult(param);

            for (Car p : page.getContent()) {

                Brand b = brandService.findById(p.getBrandId());
                p.setBrand(b);
                BrandType bt = brandTypeService.findById(p.getBrandTypeId());
                p.setBrandType(bt);
                if (null != p.getCarTypeId()) {
                    CarType carType = carTypeService.findById(p.getCarTypeId());
                    if (null != carType) {
                        p.setCarType(carType);
                    }
                }
            }

            mv.addObject("page", page);
            mv.addObject("param", param);

            return mv;
        } else {
            throw new NoPermissionException();
        }
    }


    @RequestMapping(value = "add", method = RequestMethod.GET)
    public ModelAndView add() {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("car")) {
            ModelAndView mv = new ModelAndView();

            mv.addObject("car", new Car());
            //mv.addObject("listBrand", brandService.findAll());
            //mv.addObject("listBrandType",brandTypeService.findAll());
            Long i = 1l;
            mv.addObject("listShop", shopService.selectById(i));
            //mv.addObject("listCarType",carTypeService.findAll());
            mv.addObject("company", companyService.findAll());

            mv.setViewName("car/add");

            return mv;
        } else {
            throw new NoPermissionException();
        }
    }


    @RequestMapping(value = "create", method = RequestMethod.POST)
    public @ResponseBody
    Result<Car> create(Car car, String transmissionCase) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Result<Car> result = new Result<Car>();

        if (subject.isPermitted("car")) {

            Car c = carService.findByNumber(car.getCarNumber());
            if (null != c) {
                result.setMessage("车牌号'" + c.getCarNumber() + "'已存在");
                return result;
            }

            car.setCarNumber(car.getCarNumber().toUpperCase());

            car.setTransmissionCase(TransmissionCase.MT);
            if (StringUtils.equals(transmissionCase, "AT")) {
                car.setTransmissionCase(TransmissionCase.AT);
            }

            if (null == car.getDeposit()) {
                car.setDeposit(BigDecimal.ZERO);
            }

            if (!principal.isCompanyType()) {
                car.setCompanyId(principal.getCompanyId());
            }

            carService.insertRecord(car);

            result.setSuccess(true);
            return result;
        } else {
            result.setMessage("您没有该权限");
            return result;
        }

    }

    @RequestMapping(value = "edit/{id}", method = RequestMethod.GET)
    public ModelAndView edit(@PathVariable("id") Long id) {

        Subject subject = SecurityUtils.getSubject();

        if (subject.isPermitted("car")) {
            ModelAndView mv = new ModelAndView();
            Car car = carService.findById(id);

            mv.addObject("car", car);
            mv.addObject("listBrand", brandService.findAll());
            Brand brand = brandService.findById(car.getBrandId());
            List<BrandType> brandTypes = null;
            if (brand != null) {
                brandTypes = brandTypeService.findByBrandId(brand.getId());
            }
            mv.addObject("listBrandType", brandTypes);
            mv.addObject("listCarType", carTypeService.findAll());
            mv.addObject("company", companyService.findAll());
            mv.addObject("companyId", car.getCompanyId());

            mv.setViewName("car/edit");

            return mv;
        } else {
            throw new NoPermissionException();
        }
    }

    @RequestMapping(value = "update", method = RequestMethod.POST)
    public @ResponseBody
    Result<Car> update(Car car) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        Result<Car> result = new Result<Car>();

        if (subject.isPermitted("car")) {

            if (carNumberExists(car.getCarNumber(), car.getId())) {
                result.setMessage("车牌号'" + car.getCarNumber() + "'已存在");
                return result;
            }

            Car c = carService.findById(car.getId());

            c.setName(car.getName());
            c.setCarNumber(car.getCarNumber());
            c.setBrandId(car.getBrandId());
            c.setBrandTypeId(car.getBrandTypeId());
            c.setCarNumber(car.getCarNumber());
            c.setPrice(car.getPrice());
            if (null == car.getDeposit()) {
                c.setDeposit(BigDecimal.ZERO);
            } else {
                c.setDeposit(car.getDeposit());
            }
            c.setTransmissionCase(car.getTransmissionCase());
            c.setDisplacement(car.getDisplacement());
            c.setSeating(car.getSeating());
            c.setDrivingDistance(car.getDrivingDistance());
            c.setBuyTime(car.getBuyTime());
            c.setPicture(car.getPicture());
            c.setPlace(car.getPlace());
            c.setLimitLine(car.getLimitLine());
            c.setStatus(car.getStatus());
            c.setPurpose(car.getPurpose());
            ;
            c.setProvincial(car.getProvincial());
            c.setCity(car.getCity());
            ;
            c.setCounty(car.getCounty());
            c.setCarTypeId(car.getCarTypeId());
            c.setType(car.getType());
            if (principal.isCompanyType()) {
                c.setCompanyId(car.getCompanyId());
            }

            carService.updateByPrimaryKey(c);

            result.setSuccess(true);
            return result;
        } else {
            result.setMessage("您没有该权限");
            return result;
        }

    }

    @RequestMapping(value = "delete", method = RequestMethod.POST)
    public @ResponseBody
    Result<Integer> delete(Long id, HttpServletRequest req) {

        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();

        if (subject.isPermitted("car")) {
            Result<Integer> result = new Result<Integer>();

            if (null != id) {
                Car car = carService.findById(id);

            } else {
                result.setMessage("没有可以删除的数据");
            }

            return result;
        } else {
            throw new NoPermissionException();
        }

    }

    @RequestMapping(value = "chooseBrandType", method = RequestMethod.POST)
    public @ResponseBody
    Result<BrandType> chooseBrandType(Long id) {

        Result<BrandType> result = new Result<BrandType>();
        result.setSuccess(false);
        List<BrandType> brandType = brandService.findByBrandId(id).getBrandTypes();

        if (brandType.size() != 0) {
            result.setSuccess(true);
            result.setData(brandType);
        } else {
            result.setMessage("请添加品牌类型");
        }
        return result;

    }

    @RequestMapping(value = "chooseCar", method = RequestMethod.POST)
    public @ResponseBody
    Result<Car> chooseCar(Long companyId, Long brandId, Long brandTypeId) {

        Result<Car> result = new Result<Car>();
        result.setSuccess(false);
        Subject subject = SecurityUtils.getSubject();
        Principal principal = (Principal) subject.getPrincipal();
        if (!principal.isCompanyType()) {
            companyId = principal.getCompanyId();
        } else if (principal.isCompanyType() && principal.getCompanyId().equals(companyId)) {
            companyId = null;
        }

        List<Car> list = carService.findByParams(companyId, brandId, brandTypeId);
        if (list.size() != 0) {
            result.setSuccess(true);
            result.setData(list);
        } else {
            result.setMessage("请重新选择");
        }
        return result;

    }

    private boolean carNumberExists(String carNumber, Long id) {
        Car car = carService.findByNumber(carNumber);
        if (null != car) {
            if (null != id && id.equals(car.getId())) {
                return false;
            }
            return true;
        }
        return false;
    }

    private String getBasePath(HttpServletRequest req) {

        try {
            return WebUtils.getRealPath(req.getSession().getServletContext(), "/");
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

        return StringUtils.EMPTY;
    }

    @org.springframework.web.bind.annotation.InitBinder
    public void InitBinder(WebDataBinder dataBinder) {

        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
        dateFormat.setLenient(false);
        dataBinder.registerCustomEditor(Date.class, new CustomDateEditor(
            dateFormat, true));

    }

}
